"""
本示例演示xpath的用法
"""
# 导入相关模块
from lxml import etree

html_soure = '''
        <div>
            <ul>
                 <li class="item-0" id="item-0"><a href="link1.html">first item</a></li>
                 <li class="item-1" id="item-1"><a href="link2.html">second item</a></li>
                 <li class="item-inactive" id="item-2"><a href="link3.html">third item</a></li>
                 <li class="item-1" id="item1-0"><a href="link4.html">fourth item</a></li>
                 <li class="item-0" id="item1-1"><a href="link5.html">fifth item</a>
             </ul>
         </div>
        '''


def tostring(str):
    """
    tostring 方法的使用
    :param str:
    :return:
    """
    html = etree.HTML(str)
    print(html)
    result = etree.tostring(html)
    print(result.decode("utf-8"))


def find(str):
    """
    查询内容
    :return:
    """
    # 获取某个标签的内容
    html = etree.HTML(str)
    # html_data = html.xpath("/html/body/div/ul/li/a")
    html_data = html.xpath("//div/ul/li/a")  # 通过//相对路径查询对象，//定位到根节点
    print(html_data)
    for i in html_data:
        print(i.text)  # 获取xpath对象中的文本


def find_text(str):
    """
    使用text()方法查询具体的文本
    :param str:
    :return:
    """
    html = etree.HTML(str)
    html_data = html.xpath("//div/ul/li/a/text()")
    print(html_data)
    for i in html_data:
        print(i)


def parse_html():
    """
    打开HTML文件
    TODO
    :return:
    """


def find_attr(str):
    """
    查找具体的属性值,通过/@表示查找属性值
    :param str:
    :return:
    """
    html = etree.HTML(str)
    html_data = html.xpath("//div/ul/li/a/@href")
    print(html_data)

    # 获取多个属性的值
    li_data = html.xpath("//div/ul/li")
    print(li_data)
    for li in li_data:
        print(li.xpath("./@id"))  # .代表当前路径
        print(li.xpath("./@class"))


def find_by_attr(str):
    """
    通过属性查找对象,通过[@attr=value]，可以根据属性查找对象
    可以是用and、or来组合查询元素
    :return:
    """
    html = etree.HTML(str)
    html_data = html.xpath("//div/ul/li[@class='item-0' or @id='item-1']/a/text()")
    print(html_data)
    for text in html_data:
        print(text)


def find_by_index(str):
    """
    通过first、last等顺序检索元素
    :param str:
    :return:
    """
    html = etree.HTML(str)
    html_data = html.xpath("//ul/li/a/text()")
    print(html_data)


if __name__ == "__main__":
    # tostring(html_soure)
    # find(html_soure)
    # find_text(html_soure)
    # find_attr(html_soure)
    # find_by_attr(html_soure)
    find_by_index(html_soure)
